package util

import (
	"github.com/sony/sonyflake"
	"likeadmin/core"
)

// IDUtil 通过 Sonyflake 雪花算法获得不重复id

var IDUtil = idUtil{}
var sf = initSonyflake()

type idUtil struct{}

func initSonyflake() (sf *sonyflake.Sonyflake) {
	var st sonyflake.Settings
	st.MachineID = getMID
	sf = sonyflake.NewSonyflake(st)
	if sf == nil {
		panic("sonyflake not created")
	}
	return
}

// 通过ip计算出机器ID
func getMID() (uint16, error) {
	ip := IpUtil.GetHostIp()
	mId := uint16(ip[2])<<8 + uint16(ip[3])
	//fmt.Println(ip, mId)
	return mId, nil
}

func (i idUtil) GetNewID() uint64 {
	id, err := sf.NextID()
	if err != nil {
		core.Logger.Errorf("sonyflake GetNewID err: err=[%+v]", err)
		return 0
	}
	//println(id)
	return id
}
